#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：train_dao.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/8/12 下午6:00 
@explain : 
"""
from typing import List

from sqlalchemy import desc

from app.dao.models import XlxTrain
from . import tools
from .base_dao import getDatabaseSession


class TrainQueryDao(object):
    @classmethod
    def find(cls, **kwargs) -> XlxTrain:
        with getDatabaseSession() as session:
            query = session.query(XlxTrain)
            query = tools.build_query(query, XlxTrain, **kwargs)
            results = query.first()
        return results

    @classmethod
    def list(cls, page: int = 1, page_size: int = 10, **kwargs) -> tuple[int, List[XlxTrain]]:
        with getDatabaseSession() as session:
            query = session.query(XlxTrain)
            query = tools.build_query(query, XlxTrain, **kwargs)
            total = query.count()
            # 排序分页
            offset = (page - 1) * page_size
            query = query.order_by(desc(XlxTrain.id)).offset(offset).limit(page_size)
            # 查询记录
            result = query.all()
        return total, result


class TrainOperateDao(object):
    @classmethod
    def save(cls, data: dict) -> XlxTrain:
        with getDatabaseSession() as session:
            new_data = XlxTrain(**data)
            session.add(new_data)
            session.flush()
            session.commit()
        return new_data

    @classmethod
    def update(cls, data: dict) -> XlxTrain:
        with getDatabaseSession() as session:
            query = session.query(XlxTrain).filter(XlxTrain.id == data['id']).first()
            for key, value in data.items():
                if value:
                    if hasattr(XlxTrain, key):  # 确保属性存在于模型中
                        setattr(query, key, value)
            session.commit()
        return query
